package com.momoc.mrpc.rpc.handler;

import com.momoc.mrpc.register.RegisterContext;
import com.momoc.mrpc.register.definition.MRpcRegDefinition;
import com.momoc.mrpc.rpc.message.MRpcRequestMessage;
import com.momoc.mrpc.rpc.message.MRpcResponseMessage;
import com.momoc.mrpc.util.SpringContextUtil;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.concurrent.Promise;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.ConcurrentHashMap;
import lombok.extern.slf4j.Slf4j;

/**
 * @author momoc
 * @version 1.0
 * @className MRpcRequestHandler
 * @description 处理请求入站
 * @date 2022/7/25 4:54 下午
 */
@ChannelHandler.Sharable
@Slf4j
public class MRpcResponseHandler extends SimpleChannelInboundHandler<MRpcResponseMessage> {


    //                       序号      用来接收结果的 promise 对象
    public static final Map<Integer, Promise<Object>> PROMISES = new ConcurrentHashMap<>();

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, MRpcResponseMessage msg) throws Exception {
        log.debug("{}", msg);
        // 拿到空的 promise
        Promise<Object> promise = PROMISES.remove(msg.getSequenceId());
        if (promise != null) {
            Object returnValue = msg.getData();
            Exception exceptionValue = msg.getException();
            if(exceptionValue != null) {
                promise.setFailure(exceptionValue);
            } else {
                promise.setSuccess(returnValue);
            }
        }
    }
}
